#!/usr/bin/env python

"""
   Copyright 2010 Evgen Burzak

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
"""

# Pyjon: An ECMAScript implementation in Python
# This is a command-line tool.

__author__ = "burzak"
__author_email__ = "buzzilo@gmail.com"
__date__ = "2009-10-27"

class FileNotFound(Exception): pass

import sys

import os, platform, subprocess, traceback
import jocore
from optparse import OptionParser

usage = "usage: %prog [options] script.joo" 
parser = OptionParser(usage=usage, version="%prog " + repr(jocore.__version__), add_help_option=False)
parser.set_defaults(verbose=True)
parser.add_option("-h", "--help", action="help",
                  help="show this help message and exit")
parser.add_option("-q", "--quiet", action="store_true", dest="quiet", default=False,
                  help="mute all output")
parser.add_option("-r", "--run", action="store_true", dest="run", default=False,
                  help="run the code [default]")
parser.add_option("-o",
                  metavar="FILE", dest="output", default="",
                  help="compile the code into FILE")
parser.add_option("", "--shell", dest="shell", action="store_true", default=False,
                  help="run an interactive shell")
"""
parser.add_option("-a", "--asset", dest="assets", action="append",
                    metavar="FILE", 
                    help="including FILE in compilation. Can be multiply.")
"""
parser.add_option("-L", "--lib", dest="lib_path", action="append",
                    help="add directory LIB_PATH to the list of directories to "
                         "be searched for importing [default: %s]" % ", ".join(jocore.libs))
parser.add_option("-l", "--link", dest="link", action="append",
                    metavar="CLASS",
                    help="link with CLASS (do not store code in the compilation)")
parser.add_option("", "--optimize", dest="LEVEL", default="minify",
                    help="optimization level [default: %default]")
parser.add_option("", "--disable-runtime-typing", action="store_true", dest="dynamic_typing", default=False)
parser.add_option("-d", "--debug", type="int", dest="debug_level", default=0,
                    help="debug level 1..3 (last one make lots of noise)")


def IsWindows():
  p = platform.system()
  return (p == 'Windows') or (p == 'Microsoft')

def main(argv):

    (options, args) = parser.parse_args()

    if options.lib_path:
        jocore.libs.extend(options.lib_path)

    jocore.debug = options.debug_level

    try:
        if len(args):
            script = args[0]
            if not os.path.isfile(script):
                raise FileNotFound, script + " not found"
            jocore.load(script)
        else:
            print "pyjon, v%s" % str(jocore.__version__)
            con = jocore.shell()
            while True:
                try:
                    input = raw_input("> ")
                    out = con.eval(input)
                    if out == None: pass
                    else: print out
                except (EOFError, KeyboardInterrupt):
                    print
                    return 0
                except Exception, e:
                    print e.__class__.__name__ + ": " + str(e.message)
                    if options.debug_level > 1: traceback.print_exc(file=sys.stderr)

    except Exception, e:
        if len(args):
            print "Failure in converting %s to JavaScript" % (args[0])
        print e.__class__.__name__ + ": " + str(e.message)
        if options.debug_level > 1: traceback.print_exc(file=sys.stderr)
        return 1

    if options.output:
        if options.run: jocore.run()
             
        output = open(options.output, 'w')
        output.write(jocore.compile())
        output.close()
        
    elif options.run:
        jocore.run()

    sys.stdout.flush()

    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv))
